package com.tanhua.mongo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PublishTimeLine {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 开启异步调用(spring会重新创建一个新的线程来单独执行次方法)
     */
    @Async
    public void savePublishTimeLine(Long userId, ObjectId movementId){
        //获取当前用户的好友id
        Criteria criteria = Criteria.where("userId").is(userId);

        Query query = Query.query(criteria);

        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //将friends中的好友id存入时间线表
        for (Friend friend : friends) {
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            movementTimeLine.setMovementId(movementId);
            movementTimeLine.setUserId(friend.getUserId());
            movementTimeLine.setFriendId(friend.getFriendId());
            movementTimeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movementTimeLine);
        }
    }
}
